import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:dio/dio.dart';
import 'dart:io';
import 'dart:convert';
import '../utils/http_utils.dart';
import '../model/base_model.dart';
import '../model/app_model.dart';
import '../model/user_model.dart';
import '../utils/path_utils.dart';
import '../api/api.dart';
import '../api/app_context.dart';
import '../pages/index.dart';
import 'dart:async';
import 'animation.dart';
class FaceScan extends StatefulWidget {
  FaceScan({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _FaceScanState createState() => _FaceScanState();
}

class _FaceScanState extends State<FaceScan> {
  CameraController _controller;
  //获取相机
  List<CameraDescription> cameras;
  CameraDescription frontCamera;
  CameraDescription backCamera;
  String _imageInfo;
  String _authInfo;
  Timer  countDownTimer;
  bool runAni=true;
  AnimationController ancontroller;
  LogoApp logoApp;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  @override
  void initState() {
    super.initState();
    cameras=BaseModel.of<AppModel>(context).cameras;

    //_imageInfo="图像信息";

    for(CameraDescription cameraDescription in cameras){
      if(cameraDescription.lensDirection==CameraLensDirection.back){
        backCamera=cameraDescription;
      }
      if(cameraDescription.lensDirection==CameraLensDirection.front){
        frontCamera=cameraDescription;
      }
    }
    //计时器
    countDownTimer = new Timer.periodic(new Duration(seconds: 2), (timer){
      print(timer.tick);
      _onCapture();
    });

    logoApp= LogoApp();
    _controller=CameraController(frontCamera==null?backCamera:frontCamera, ResolutionPreset.low);
    _controller.initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }



  //拍照

  Future<void> _onCapture() async {
    String filePath;

    await PathUtils.instance.then((path) async {
      filePath = '${path.tempDirectory.path}/${timestamp()}.jpg';
      //filePath = '${path.documentsDirectory.path}/${timestamp()}.txt';
      // new File(filePath).writeAsStringSync("1123344");
      await _controller.takePicture(filePath);
      File file=File(filePath);
      file.readAsBytes().then((bytes){
        String base64str=base64Encode(bytes);
        print("bytes.length:${bytes.length}:${DateTime.now()}");
        //get accessToken
        getAuth().then((token){
          print("after getAuth:${DateTime.now()}");
          print("accessToken:$token");
          getFaceInfo(token,base64str).then((resp){
            print(resp);
            print("after getFace:${DateTime.now()}");
            Map face=resp.data;
            if(face['error_code']!=0){
             // setState(() {
                _imageInfo=null;
            //  });
              return;
            }
            int age=face['result']['face_list'][0]['age'];
            String gender=face['result']['face_list'][0]['gender']['type'];
            print('age:$age');
            print('gender:$gender');
            //_login(gender, age);
            countDownTimer.cancel();
           _controller.dispose();
            logoApp?.dispose();
           Navigator.pop(context,"age:$age,gender:$gender");
          });
        }
        );
      });
    });

    return filePath;
  }
  @override
  Widget build(BuildContext context) {
    if(_controller==null||!_controller.value.isInitialized) return Text("未找到相机");
    return Column(
        children: <Widget>[
          SizedBox(
            height: 50,
          ),
         Center(
           child: Text(widget.title,style: TextStyle(fontSize: 20),),
         ),
          Container(
           padding: EdgeInsets.only(top: 50),
           child: new Align(
              alignment: Alignment.center,
              child: Container(
                        decoration: BoxDecoration(border: Border.all(width:5, color: Colors.blue),
                            shape: BoxShape.rectangle,
                            borderRadius:
                            const BorderRadius.all(const Radius.circular(360.0))),
                        child: new ClipRRect(
                          borderRadius: const BorderRadius.all(const Radius.circular(180.0)),
                          child:
                          Container(
                            width: 300.0,
                                height: 300.0,
                                child:
                                    Stack(
                                      children: <Widget>[
                                       ListView(
                                         children: <Widget>[
                                           Container(
                                             width: 300,
                                             child: AspectRatio(
                                               aspectRatio: _controller.value.aspectRatio,
                                               child: CameraPreview(_controller),
                                             ),
                                           ),
                                         ],
                                       ),
                                       logoApp,
                                      ],
                                    )
                              ),
                        ),
                      ),
                    //  LogoApp()
            ),
           // flex: 4,

          ),
          Expanded(
            flex: 1,
            child: Container(
                margin: EdgeInsets.only(top: 30.0),
                child: Text(
                  _imageInfo!=null?_imageInfo:'',
                  style: TextStyle(color: Colors.red),
                ),
            ),
          ),
        ],
      );
  }

  @override
  void dispose() {
    countDownTimer.cancel();
    super.dispose();
    _controller.dispose();
  }

  String timestamp() => DateTime.now().millisecondsSinceEpoch.toString();

  //获取access_token
  Future<String> getAuth() async{
    if(_authInfo!=null) return Future.value(_authInfo);
    String ak='ozt0wf9Un27lGz5XdSXzQpdk';
    String sk='oGMj53TgeI0t68hIAw5cOHq0CzgUPS1E';
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
    String getAccessTokenUrl = authHost
        // 1. grant_type为固定参数
        + "grant_type=client_credentials"
        // 2. 官网获取的 API Key
        + "&client_id=" + ak
        // 3. 官网获取的 Secret Key
        + "&client_secret=" + sk;

    BaseResp resp= await HttpUtils().post(getAccessTokenUrl);
    _authInfo=resp.data['access_token'];
    return resp.data['access_token'];

  }
  //人脸识别
  Future<BaseResp> getFaceInfo(String accessToken,String base64Str) async{
    String url='https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=$accessToken';
    Map data={'image':base64Str,'image_type':'BASE64','face_field':'age,gender'};
    Options options=Options();
    options.contentType=ContentType.json;
    return await HttpUtils().post(url,
        data: data,
        options: options
    );
  }
}
